package com.ric.service.sysuser.impl;

import com.ric.dao.mapper.sysResource.SysResourceMapper;
import com.ric.dao.mapper.sysUser.SysUserMapper;
import com.ric.dao.model.sysResource.SysResource;
import com.ric.dao.model.sysUser.SysUser;
import com.ric.service.sysuser.SysUserService;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Created by Administrator on 2017/5/26.
 */
@Service
public class SysUserServiceImpl implements SysUserService {

    private static final Logger logger = LoggerFactory.getLogger(SysUserServiceImpl.class);

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SysResourceMapper sysResourceMapper;

    @Override
    public void addUser(SysUser user) {
        sysUserMapper.insert(user);
    }

    /**
     * 登录逻辑
     * 1、先根据用户名查询用户对象
     * 2、如果有用户对象，则继续匹配密码
     * 如果没有用户对象，则抛出异常
     * @param userName
     * @param password
     * @return
     */
    @Override
    public SysUser login(String userName, String password) {
        SysUser user = sysUserMapper.selectByUserName(userName);
        // 密码匹配的工作交给 Shiro 去完成
        if(user == null ){
            // 因为缓存切面的原因,在这里就抛出用户名不存在的异常
            throw new UnknownAccountException("用户名不存在(生产环境中应该写:用户名和密码的组合不正确)");
        }else if(user.getStatus() == 1){
            throw new LockedAccountException("用户已经被禁用，请联系管理员启用该账号");
        }
        return user;
    }

    /**
     * 查询指定用户 id 所拥有的权限
     * @param userId
     * @return
     */
    @Override
    public List<SysResource> listAllResource(String userId) {
        return sysResourceMapper.listAllResources(userId);
    }


    /**
     * 查询指定用户所指定的角色字符串列表
     * @param userId
     * @return
     */
    @Override
    public List<String> listRoleNameByUser(String userId) {
        return sysUserMapper.listRoleNameByUser(userId);
    }
}
